import React from 'react';

let observers = {};
let uuid = 0;

function genUID() {
    return ++uuid;
}


export function ipc(name, listener) {
    return (Wrapper) => {
        const componentWillMount = Wrapper.prototype.componentWillMount;
        const componentWilUnmount = Wrapper.prototype.componentWillUnmount;
        const uid = genUID();
        Wrapper.prototype.componentWillMount = function() {
            if (observers[name] === undefined) {
                observers[name] = [];
            }
            observers[name].push({
                key: uid,
                listener: listener.bind(this)
            });
            componentWillMount && componentWillMount();
        }

        Wrapper.prototype.componentWillUnmount = function() {
            if (observers[name]) {
                const index = observers[name].findIndex(item => item.key === uid);
                observers[name].splice(index, 1);
            }
            componentWilUnmount && componentWilUnmount();
        }
        return Wrapper;
    }
}

export function send(name, params) {
    if (observers[name]) {
        for (let observer of observers[name]) {
            observer.listener(params);
        }
    }
}
